package com.factory.test.activity;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.util.Log;
import android.widget.SeekBar;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.factory.test.base.BaseTestActivity;
import com.factory.test.R;
import com.factory.test.databinding.ActivitySoundBinding;

import java.io.File;
import java.io.IOException;

/**
 * 声音录音测试
 */
public class SoundActivity extends BaseTestActivity {

    private ActivitySoundBinding binding;
    private MediaPlayer mediaPlayer;         //mediaPlayer对象
    private MediaRecorder mRecorder;
    private AudioManager mAudioManager;
    private String fileName = "/sdcard/Android/soundTest.3gp";
    private int mMaxVolume;
    private int mNowVolume;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_sound);
        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mNowVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        fileName = getExternalCacheDir() + "/soundTest.3gp";
        binding.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                mNowVolume = mMaxVolume * seekBar.getProgress() / seekBar.getMax();
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mNowVolume, AudioManager.FLAG_PLAY_SOUND);

                mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
                mNowVolume = mMaxVolume * seekBar.getProgress() / seekBar.getMax();
                mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, mNowVolume, AudioManager.FLAG_PLAY_SOUND);

                mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
                mNowVolume = mMaxVolume * seekBar.getProgress() / seekBar.getMax();
                mAudioManager.setStreamVolume(AudioManager.STREAM_RING, mNowVolume, AudioManager.FLAG_PLAY_SOUND);

                binding.value.setText(String.format("当前音量: %d", progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        binding.seekBar.setProgress(binding.seekBar.getMax() * mNowVolume / mMaxVolume);


        recorder();
    }


    private void recorder() {
        try{
            File file = new File(fileName);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }

            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            mRecorder.setOutputFile(fileName);
            try {
                mRecorder.prepare();
            } catch (IOException e) {
                Log.e(tag, "MediaRecorder fail ", e);
            }
            mRecorder.start();
            binding.message.setText("录音中,请稍后...");

            soundRecordingTimer = new SoundRecordingTimer();
            soundRecordingTimer.start();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private SoundRecordingTimer soundRecordingTimer;
    private class SoundRecordingTimer extends CountDownTimer{
        private long millisInFuture;
        public SoundRecordingTimer() {
            super(5100, 1000);
            this.millisInFuture = 5100;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            long t = millisUntilFinished / 1000;
            if (t <= 0) {
                t = 0;
            }
            binding.message.setText(String.format("录音中,请稍后...(%s)", t));
        }

        @Override
        public void onFinish() {
            soundR.run();
        }
    }


    private PlayTimer playTimer;
    private class PlayTimer extends CountDownTimer{
        private long millisInFuture;
        public PlayTimer() {
            super(5100, 1000);
            this.millisInFuture = 5100;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            long t = millisUntilFinished / 1000;
            if (t <= 0) {
                t = 0;
            }
            binding.message.setText(String.format("录制完成，播放音频中...(%s)", t));
        }

        @Override
        public void onFinish() {
        }
    }




    Runnable soundR = new Runnable() {
        @Override
        public void run() {
            mRecorder.stop();
            binding.message.setText("录制完成，播放音频中...");
            mRecorder.release();
            mRecorder = null;
            mediaPlayer = new MediaPlayer();
            try {
                mediaPlayer.setDataSource(fileName);
                playTimer = new PlayTimer();
                playTimer.start();
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        playTimer.cancel();
                        SystemClock.sleep(100);
                        binding.message.setText("音频播放完毕");
                    }
                });
                mediaPlayer.prepare();
                mediaPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(soundRecordingTimer != null){
            soundRecordingTimer.cancel();
        }

        if(playTimer != null){
            playTimer.cancel();
        }

        if(mediaPlayer != null){
            mediaPlayer.stop();
            mediaPlayer.release();
        }

        if(mRecorder != null){
            mRecorder.stop();
            mRecorder.release();
        }

        if(mediaPlayer != null){
            mediaPlayer.release();
        }

        File file = new File(fileName);
        if(file.exists()){
            file.delete();
        }
    }
}
